"use client"

import { ReportType } from "@/type/report"
import { Button, Form, Modal, ModalBody, ModalContent, ModalHeader, Input, Select, SelectItem, Divider, TimeInput, Drawer, DrawerContent, DrawerHeader, DrawerBody, DrawerFooter, Textarea } from "@nextui-org/react";
import { useEffect, useMemo, useState } from "react";
import { Time } from "@internationalized/date";
import { DeleteIcon } from "../TableView";
import { plusReport } from "@/api/team/plus";
import toast from "react-hot-toast";
import { useAppDispatch, useAppSelector } from "@/lib/hooks";
import { getLastId, updateReportData } from "@/lib/features/report/reportSlice";
import { updateReport, updateReportRID } from "@/api/team/update";
import { getCpxm } from "@/api/team/cp/cpxm";
import CPXMTYPE from "@/type/cpxm";
import CPXHTYPE from "@/type/cpxh";
import { getCp } from "@/api/team/cp/cp";
import { CPXH } from "../Report/Product";
import { STATUS } from "../Report";
import { TeamUserList } from "@/type/user";
import { getTeamUserList } from "@/api/team/tember/get";

type CPXHS = {
    key: string,
    name: string,
    price: number
}

const DataModal = ({ menuChange, action, data, isOpen, onClose, sort, team_id }: { menuChange: (v: STATUS) => void, action: number, data: ReportType | null, isOpen: boolean, onClose: () => void, sort: number, team_id: number }) => {

    const [detail, setDetail] = useState<ReportType | null>(null);

    const [czys, setCzys] = useState<TeamUserList[] | null>()

    const [isDrawerOpen, setIsDrawerOpen] = useState(false)

    const [czyId, setCzyId] = useState<string>("")
    const [cpxmId, setCpxmId] = useState<string>("")

    const handleSelectCZY = () => {
        if (data) {
            const { id } = czys?.find((item) => item.name == data.czy) ?? {}
            const { key } = CPXMS.find((item) => item.label == data.cpxm) ?? {}
            setCpxmId(key + "")
            setCzyId(id + "")
            if (!(data.xh == "" || data.xh == undefined || data.xh == null)) {
                setCpxhs(JSON.parse(data.xh))
            }


        }
    }

    const [cpxhs, setCpxhs] = useState<CPXHS[]>([
        {
            key: "0",
            name: "0",
            price: 0
        },
    ]);

    const [CPXMS, setCPXMS] = useState<CPXMTYPE[]>([])
    const [CPXH, setCPXH] = useState<CPXHTYPE[]>([])

    const getSelectData = async () => {
        const cpxm = await getCpxm()
        const result = await getTeamUserList(team_id)
        if (result.code == 200) {
            setCzys(result.data)
        }
        if (cpxm.code == 200) {
            setCPXMS(cpxm.data.data)
            getSelectDataXH(cpxm.data.data[0]?.id ?? 0)
        }
    }

    const getSelectDataXH = async (id: number) => {
        const result = await getCp(id)
        if (result.code == 200) {
            const data = result.data.data as CPXH[]
            const dataArray: CPXHTYPE[] = []
            data.forEach((item) => {
                dataArray.push({
                    id: item.cpxh_id,
                    key: item.xhkey,
                    label: item.xhname
                })
            })
            setCPXH(dataArray)
        } else {
            setCPXH([])
        }
    }

    useEffect(() => {
        if (action == 1) {
            setDetail({
                tjbh: 0,
                cpxm: "DM5.0",
                jpsj: 450,
                kssj: new Time(8).toString(),
                jssj: new Time(20).toString(),
                lb: '0',
                scgs: 12,
                wssx: "",
                yxgs: 12,
                llcn: 0,
                trtj: 1,
                scxl: "0",
                jhsl: 0,
                sjwc: 0,
                wcl: "0",
                tjsj: 0,
                bls: 0,
                trry: 1,
                czy: "",
                xh: "",
                sort: sort,
                team_id: team_id,
                bz: ""
            } as ReportType);
            setCpxhs([
                {
                    key: "0",
                    name: "0",
                    price: 0
                }
            ])
            getSelectData()
        } else {
            setDetail({
                ...data as ReportType
            });
        }
        handleSelectCZY()
    }, [data])

    const toHours = (v: string): number => {
        const dt = new Date(new Date().toLocaleDateString() + " " + v);
        return dt.getHours();
    }

    const deleteCpxhs = (key: string) => {
        setCpxhs(cpxhs.filter(o => o.key !== key))
    }

    const calcProductivity = useMemo(() => {
        if (!detail) {
            return "0%"
        }
        // 生产效率计算
        const result = ((detail.sjwc - detail?.bls) / detail.llcn) * 100
        const wclc = ((detail.sjwc) / detail.jhsl) * 100
        setDetail({ ...detail, wcl: wclc.toFixed(2) + "%", scxl: result.toFixed(1) + "%" })
    }, [detail?.sjwc, detail?.jhsl, detail?.bls, detail?.llcn])

    const calcTheoreticalCapacity = useMemo(() => {
        if (!detail) {
            return "0%"
        }
        // 计算理论产能
        const dt = new Date(new Date().toLocaleDateString() + " " + detail?.jssj);
        const dt1 = new Date(new Date().toLocaleDateString() + " " + detail?.kssj);
        const result = (((dt.getHours() - dt1.getHours()) - detail.tjsj) * 3600) / detail.jpsj * detail.trtj
        if (detail?.jpsj == 0 || detail?.jpsj == null || detail?.jpsj == undefined) {
            setDetail({ ...detail, scgs: dt.getHours() - dt1.getHours(), yxgs: ((dt.getHours() - dt1.getHours()) - detail.tjsj) })
        } else {
            setDetail({ ...detail, llcn: result, scgs: dt.getHours() - dt1.getHours(), yxgs: ((dt.getHours() - dt1.getHours()) - detail.tjsj) })
        }
    }, [detail?.jpsj, detail?.kssj, detail?.jssj, detail?.tjsj, detail?.trtj])

    const id = useAppSelector(getLastId)

    const dispatch = useAppDispatch()

    return (
        <>
            <Drawer isDismissable={false} placement="top" size="sm" isOpen={isDrawerOpen} onOpenChange={(v) => setIsDrawerOpen(v)} onClose={() => setIsDrawerOpen(false)}>
                <DrawerContent>
                    <DrawerHeader className="flex flex-col gap-1">型号列表</DrawerHeader>
                    <DrawerBody>
                        {

                            cpxhs.map((o, i) => {
                                return (
                                    <div
                                        className="flex items-center justify-between gap-2"
                                        key={i}
                                    >
                                        {
                                            CPXH.length == 0 ? (
                                                <>
                                                    <Button onPress={() => menuChange(2)} radius="sm" color="danger" className="p-0" size="lg" fullWidth>
                                                        <span className="text-sm">添加产品型号</span>
                                                    </Button>
                                                </>
                                            ) : (
                                                <>
                                                    <Select

                                                        color={action == 3 ? "secondary" : "default"}
                                                        size="sm"
                                                        isDisabled={action == 3}
                                                        className="w-max-[140px]"
                                                        defaultSelectedKeys={[o.key]}
                                                        label="型号"
                                                        value={o?.name}
                                                        onSelectionChange={(v) => {
                                                            const result = CPXH.find((i) => i.key == v.currentKey)
                                                            o.name = result?.label || "";
                                                            o.key = result?.key || "";
                                                            setCpxhs([...cpxhs])
                                                        }}
                                                    >
                                                        {
                                                            CPXH.filter((value) => {
                                                                const arr = []
                                                                for (let i = 0; i < cpxhs.length; i++) {
                                                                    if (cpxhs[i].key != o.key) {
                                                                        arr.push(cpxhs[i].key)
                                                                    }
                                                                }
                                                                return arr.includes(value.key) == false
                                                            }).map((item) => (
                                                                <SelectItem key={item.key}>{item.label}</SelectItem>
                                                            ))
                                                        }

                                                    </Select>
                                                </>
                                            )
                                        }
                                        <Input
                                            isReadOnly={action == 3}
                                            isRequired
                                            color={action == 3 ? "secondary" : "success"}
                                            className="w-[140px]"
                                            size="sm"
                                            label="Price"
                                            value={o.price + ""}
                                            onValueChange={(v) => { o.price = Number(v); setCpxhs([...cpxhs]) }}
                                            labelPlacement="inside"
                                            type="number"
                                        />
                                        {
                                            action == 3 ? null : (
                                                <Button radius="full" isIconOnly onPress={() => deleteCpxhs(o.key)} size="sm" color="danger">
                                                    <DeleteIcon width={16} height={16} />
                                                </Button>
                                            )
                                        }
                                    </div>
                                )
                            })
                        }
                    </DrawerBody>
                    {
                        action == 3 ? null : (
                            <DrawerFooter>
                                <Button onPress={() => setCpxhs([...cpxhs, { key: "", name: "", price: 0 }])} size="sm" fullWidth color="primary">添加</Button>
                                <Button onPress={() => {
                                    let sum = 0
                                    cpxhs.forEach(e => {
                                        sum += e.price
                                    })
                                    setDetail({ ...detail as ReportType, xh: JSON.stringify(cpxhs), sjwc: sum })
                                    setIsDrawerOpen(false)

                                }} size="sm" fullWidth color="success">保存</Button>
                            </DrawerFooter>
                        )
                    }
                </DrawerContent>
            </Drawer>
            <Modal isDismissable={false} className="text-white" isOpen={isOpen} placement="top-center" onClose={onClose}>
                <ModalContent>
                    <ModalHeader className="flex flex-col gap-1 text-white">
                        {
                            (action == 1) ? "添加" : (action == 2) ? "编辑" : "预览"
                        }
                    </ModalHeader>
                    <ModalBody>
                        <Form
                            className="w-full flex flex-col"
                            validationBehavior="native"
                            onSubmit={async (e) => {
                                e.preventDefault();
                                if (action == 2) {
                                    const result = await updateReport(detail as ReportType)
                                    if (result.code == 200) {
                                        dispatch(updateReportData({ ...detail } as ReportType))
                                        if (detail != null) {
                                            const uId = czys?.find((item) => item.name == detail.czy)?.u_id ?? null
                                            await updateReportRID(detail.id as number, uId)
                                        }
                                        toast.success(result.data)
                                    } else {
                                        toast.error(result.data)
                                    }
                                } else {
                                    const result = await plusReport(detail as ReportType)
                                    if (result.code == 200) {
                                        dispatch(updateReportData({ ...detail, id: id + 1 } as ReportType))
                                        toast.success(result.data)
                                    } else {
                                        toast.error(result.data)
                                    }
                                }
                                onClose()
                            }}
                        >
                            <div className="flex gap-1">
                                <Input
                                    size="sm"
                                    isRequired
                                    color={action == 3 ? "secondary" : "default"}
                                    label="台架编号"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, tjbh: Number(v.replace(/\D/g, '')) })}
                                    value={detail?.tjbh + ""}
                                    isReadOnly={action == 3}
                                />
                                {
                                    CPXMS.length == 0 ? (
                                        <>
                                            <Button onPress={() => menuChange(2)} radius="sm" color="danger" className="p-0" size="lg" fullWidth>
                                                <span className="text-sm">添加产品</span>
                                            </Button>
                                        </>
                                    ) :
                                        (
                                            <>
                                                <Select
                                                    isDisabled={action == 3}
                                                    color={action == 3 ? "secondary" : "default"}
                                                    isRequired
                                                    size="sm"
                                                    selectedKeys={[cpxmId]}
                                                    className="w-max-[140px]"
                                                    label="产品项目"
                                                    value={detail?.cpxm}
                                                    onSelectionChange={(v) => {
                                                        const res = CPXMS.find((i) => i.key == v.currentKey)
                                                        setCpxmId(res?.key + "")
                                                        setDetail({ ...detail as ReportType, cpxm: res?.label + "" })
                                                        if (res != undefined) {
                                                            getSelectDataXH(res.id as number)
                                                        }
                                                    }}
                                                >
                                                    {CPXMS.map((item) => (
                                                        <SelectItem key={item.key}>{item.label}</SelectItem>
                                                    ))}
                                                </Select>
                                            </>
                                        )
                                }
                                <Input
                                    isReadOnly={action == 3}
                                    color={action == 3 ? "secondary" : "default"}
                                    size="sm"
                                    label="节拍时间(s)"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, jpsj: Number(v.replace(/\D/g, '')) })}
                                    value={detail?.jpsj + ""}
                                />
                            </div>
                            <Divider />
                            <div className="flex gap-1">
                                <TimeInput
                                    color={action == 3 ? "secondary" : "default"}
                                    onChange={(e) => {
                                        setDetail({ ...detail as ReportType, kssj: e?.toString() + "" })
                                    }} isReadOnly={action == 3} hourCycle={24} value={new Time(toHours(detail?.kssj + ""))} minValue={new Time(8)} className="w-max-[105px]" size="sm" isRequired errorMessage="请输入正确的时间" label="开始时间(H)" />
                                <TimeInput
                                    color={action == 3 ? "secondary" : "default"}
                                    onChange={(e) => {
                                        setDetail({ ...detail as ReportType, jssj: e?.toString() + "" })
                                    }} isReadOnly={action == 3} hourCycle={24} value={new Time(toHours(detail?.jssj + ""))} maxValue={new Time(24)} className="w-max-[105px]" size="sm" isRequired errorMessage="请输入正确的时间" label="结束时间(H)" />
                                <Input
                                    color={action == 3 ? "secondary" : "default"}
                                    isReadOnly={action == 3}
                                    size="sm"
                                    label="连班"
                                    isRequired
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, lb: (Number(v.replace(/\D/g, '')) > 3 ? "3" : v.replace(/\D/g, '')) + "" })}
                                    value={detail?.lb}
                                />
                            </div>
                            <div className="flex gap-1">
                                <Input
                                    isReadOnly={action == 3}
                                    size="sm"
                                    isRequired
                                    label="生产工时(H)"
                                    color="secondary"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, scgs: (Number(v.replace(/\D/g, '')) > 15 ? 15 : Number(v.replace(/\D/g, ''))) })}
                                    value={detail?.scgs + ""}
                                />
                                <Input
                                    isReadOnly={action == 3}
                                    color={action == 3 ? "secondary" : "default"}
                                    size="sm"
                                    label="5S收线"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, wssx: v })}
                                    value={detail?.wssx}
                                />
                                <Input
                                    isReadOnly={action == 3}
                                    size="sm"
                                    isRequired
                                    label="有效工时(H)"
                                    color="secondary"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, yxgs: (Number(v.replace(/\D/g, '')) > 15 ? 15 : Number(v.replace(/\D/g, ''))) })}
                                    value={detail?.yxgs + ""}
                                />
                            </div>
                            <Divider />
                            <div className="flex gap-1">
                                <Input
                                    isReadOnly={action == 3}
                                    color={action == 3 ? "secondary" : "default"}
                                    size="sm"
                                    isRequired
                                    label="投入台架"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, trtj: Number(v.replace(/\D/g, '')) })}
                                    value={detail?.trtj + ""}
                                />
                                <Input
                                    size="sm"
                                    isRequired
                                    label="理论产能"
                                    // isReadOnly
                                    isReadOnly={(action == 3) || (!(detail?.jpsj == 0 || detail?.jpsj == null || detail?.jpsj == undefined))}
                                    color={(action == 3) || !(detail?.jpsj == 0 || detail?.jpsj == null || detail?.jpsj == undefined) ? "secondary" : "default"}
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    defaultValue={calcTheoreticalCapacity}
                                    onValueChange={(v) => { setDetail({ ...detail as ReportType, llcn: Number(v.replace(/\D/g, '')) }) }}
                                    type="text"
                                    value={detail?.llcn + ""}
                                />
                                <Input
                                    isReadOnly={action == 3}
                                    size="sm"
                                    isRequired
                                    label="生产效率/%"
                                    color="secondary"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    value={detail?.scxl}
                                />
                            </div>
                            <div className="flex gap-1">
                                <Input
                                    isReadOnly={action == 3}
                                    size="sm"
                                    isRequired
                                    color={action == 3 ? "secondary" : "default"}
                                    label="计划数量"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, jhsl: Number(v.replace(/\D/g, '')) })}
                                    value={detail?.jhsl + ""}
                                />
                                <Input
                                    isReadOnly={action == 3}
                                    size="sm"
                                    isRequired
                                    color="secondary"
                                    label="实际完成"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    defaultValue={calcProductivity}
                                    type="text"
                                    value={detail?.sjwc + ""}
                                />
                                <Button color="warning" size="lg" onPress={() => setIsDrawerOpen(true)} radius="sm" className="px-0 border-none" fullWidth>
                                    <span className="text-xs">型 号</span>
                                </Button>
                            </div>
                            <Divider />
                            <div className="flex gap-1">
                                <Input
                                    isReadOnly={action == 3}
                                    size="sm"
                                    label="完成率/%"
                                    color="secondary"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    value={detail?.wcl + ""}
                                />
                                <Input
                                    size="sm"
                                    color={action == 3 ? "secondary" : "default"}
                                    isReadOnly={action == 3}
                                    isRequired
                                    label="不良数"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, bls: Number(v.replace(/\D/g, '')) })}
                                    value={detail?.bls + ""}
                                />
                                <Input
                                    size="sm"
                                    isReadOnly={action == 3}
                                    isRequired
                                    color={action == 3 ? "secondary" : "default"}
                                    label="投入人员"
                                    labelPlacement="inside"
                                    className="w-max-[105px]"
                                    type="text"
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, trry: Number(v.replace(/\D/g, '')) })}
                                    value={detail?.trry + ""}
                                />
                            </div>
                            <div className="flex gap-1 w-full">
                                <Input
                                    size="sm"
                                    color={action == 3 ? "secondary" : "default"}
                                    isRequired
                                    isReadOnly={action == 3}
                                    label="停机时间"
                                    className="w-2/4"
                                    labelPlacement="inside"
                                    type="text"
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, tjsj: Number(v.replace(/\D/g, '')) })}
                                    value={detail?.tjsj + ""}
                                />
                                <Select
                                    isRequired
                                    size="sm"
                                    color={action == 3 ? "secondary" : "default"}
                                    className="w-2/4"
                                    label="操作员"
                                    isDisabled={action == 3}
                                    value={detail?.czy}
                                    selectedKeys={[czyId]}
                                    onSelectionChange={(v) => {
                                        const res = czys?.find((it) => it.id + "" == v.currentKey)
                                        setCzyId(res?.id + "")
                                        setDetail({ ...detail as ReportType, czy: res?.name as string })
                                    }}
                                >
                                    {
                                        czys != null ?
                                            czys.map((item) => (
                                                <SelectItem key={item.id}>{item.name}</SelectItem>
                                            ))
                                            : null
                                    }
                                </Select>
                            </div>
                            <Divider />
                            <div className="flex gap-1 w-full">
                                <Textarea
                                    isClearable
                                    color={action == 3 ? "secondary" : "default"}
                                    isReadOnly={action == 3}
                                    size="sm"
                                    value={detail?.bz}
                                    onValueChange={(v) => setDetail({ ...detail as ReportType, bz: v })}
                                    label="异常反馈/备注"
                                    variant="bordered"
                                />
                            </div>
                            <div className="flex justify-end gap-2 w-full">
                                <Button size="sm" color="danger" onPress={onClose}>
                                    {(action == 3) ? "关闭" : "取消"}
                                </Button>
                                {
                                    !(action == 3) && (
                                        <Button type="submit" size="sm" color="primary">
                                            {
                                                (action == 2) ? "保存" : "添加"
                                            }
                                        </Button>
                                    )
                                }
                            </div>
                        </Form>
                    </ModalBody>
                </ModalContent>
            </Modal >
        </>
    )
}

export default DataModal